package com.itcast.peft.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itcast.peft.service.AnswerService;

@RestController
@RequestMapping("/answer")
public class AnswerController {

    @Autowired
    private AnswerService answerService;

    /**
     * objectMapper用于序列化
     */
    private ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/answerByTeacher")
    @ResponseBody
    public String answerByTeacher(@RequestParam("batchId") String batchId) throws IOException {
        answerService.answerByTeacher(batchId);
        return "success";
    }

    @GetMapping("/answerByStudent")
    @ResponseBody
    public String answerByStudent(@RequestParam("batchId") String batchId) throws IOException {
        answerService.answerByStudent(batchId);
        return "success";
    }
    
    @GetMapping("/answerByUserOpt")
    @ResponseBody
    public String answerByUserOpt(@RequestParam("batchId") String batchId) throws IOException {
        answerService.answerByUserOpt(batchId);
        return "success";
    }
    
    @GetMapping("/answerByHealthOpt")
    @ResponseBody
    public String answerByHealthOpt(@RequestParam("batchId") String batchId) throws IOException {
        answerService.answerByHealthOpt(batchId);
        return "success";
    }

    @GetMapping("/convertAnswerGroupToLineMessage")
    @ResponseBody
    public ResponseEntity<byte[]> convertAnswerGroupToLineMessage(
            @RequestParam("ansGroup") String ansGroup,
            @RequestParam(name = "systemMessage", required = false) String systemMessage)
            throws IOException {
        try (ByteArrayOutputStream bios = new ByteArrayOutputStream()) {
            var allLines = answerService.convertAnswerGroupToLineMessage(ansGroup, systemMessage);
            for (var l : allLines) {
                String jsonLine = objectMapper.writeValueAsString(l) + '\n';
                bios.writeBytes(jsonLine.getBytes());
            }
            // 输出数据为下载文件的形式
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON)
                    .header("Content-disposition", "attachment; filename=data.jsonl").body(bios.toByteArray());
        }
    }

}
